package com.example.my_self_view.util

import java.text.SimpleDateFormat
import java.util.*

/**
 * Author: filowl
 * Description: 时间工具类
 * Date: 2024/4/28 10:28
 **/
object TimeUtil {

    val oneDay = 24L * 60L * 60L * 1000L
    private var startTime = 0L
    private var nowTime = 0L
    private var endTime = 0L

    fun TIME_FORMAT(format: String, currentTime: Long): String = SimpleDateFormat(format, Locale.CHINA).format(currentTime)

    fun TIME_PARSE(format: String, currentTime: String): Long = SimpleDateFormat(format, Locale.CHINA).parse(currentTime)?.time ?: 0

    fun timestamp(time: Long): Long {
        val diff = time - System.currentTimeMillis()
        val days = diff / (1000 * 60 * 60 * 24)
        val hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        val minutes = diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) / (1000 * 60)
        return days * 24 * 60 + hours * 60 + minutes
    }

    //时间格式化
    fun timeFormat(format: String?, currentTime: Long): String? {
        val sdf = SimpleDateFormat(format, Locale.SIMPLIFIED_CHINESE)
        return sdf.format(currentTime)
    }

    fun dateFormat(time: String): String {
        val timeStr = StringBuilder()
        timeStr.append(time.substring(0, 4)).append("-")
            .append(time.substring(4, 6)).append("-")
            .append(time.substring(6, 8)).append(" ")
            .append(time.substring(8, 10)).append(":")
            .append(time.substring(10, 12)).append(":")
            .append(time.substring(12))
        return String(timeStr)
    }

    fun formatDate(time: String): String {
        val timeStr = StringBuilder()
        timeStr.append(time.substring(0, 4)).append("-")
            .append(time.substring(4, 6)).append("-")
            .append(time.substring(6, 8))
        return String(timeStr)
    }

    /**
     * 判断两个时间大小
     */
    fun beforeThanAfter(start: String, end: String): Boolean {
        val str = TIME_FORMAT("yyyy/MM/dd", Date().time)
        startTime = Date("$str $start").time
        endTime = Date("$str $end").time

        return startTime >= endTime
    }

    fun getTodayStart(): String {
        val dateStr = TIME_FORMAT("yyyy-MM-dd", System.currentTimeMillis())
        return "$dateStr 00:00:00"
    }

    fun getTodayEnd(): String {
        val dateStr = TIME_FORMAT("yyyy-MM-dd", System.currentTimeMillis())
        return "$dateStr 23:59:59"
    }

    // 获取本周周一日期
    fun getFirstWeekDate(): String {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
        val dateStr = TIME_FORMAT("yyyy-MM-dd", calendar.time.time)
        return "$dateStr 00:00:00"
    }

    // 获取本周周末日期
    fun getWeekEndDate(): String {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
        calendar.add(Calendar.WEEK_OF_YEAR, 1)
        val dateStr = TIME_FORMAT("yyyy-MM-dd", calendar.time.time)
        return "$dateStr 23:59:59"
    }

    // 获取本月一号日期
    fun getFirstMonthDate(): String {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DAY_OF_MONTH, 1)
        val dateStr = TIME_FORMAT("yyyy-MM-dd", calendar.time.time)
        return "$dateStr 00:00:00"
    }

    // 获取本月月末日期
    fun getMonthEndDate(): String {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
        val dateStr = TIME_FORMAT("yyyy-MM-dd", calendar.time.time)
        return "$dateStr 23:59:59"
    }

    // 获取前三个月一号日期
    fun getFirstDateBeforeMonth(n: Int): String {
        val calendar = Calendar.getInstance()
        // 获取当前月份
        val currentMonth = calendar[Calendar.MONTH]
        // 输出前n个月的1号
        calendar.set(Calendar.MONTH, currentMonth - n)
        calendar.set(Calendar.DAY_OF_MONTH, 1)
        val date = TIME_FORMAT("yyyy-MM-dd", calendar.time.time)
        return "$date 00:00:00"
    }

    /**
     * 判断当天某个时间是否某个区间内
     */
    fun estimateDayTime(begin: String, end: String, time: String): Boolean {
        val str = TIME_FORMAT("yyyy/MM/dd", Date().time)

        startTime = Date("$str $begin").time
        nowTime = Date("$str $time").time
        endTime = Date("$str $end").time

        return nowTime in startTime until (endTime + 1)
    }

    /**
     * 判断当天时间是否某个区间内
     */
    fun estimateTime(begin: String, end: String): Boolean {
        val str = TIME_FORMAT("yyyy/MM/dd", Date().time)

        startTime = Date("$str $begin").time
        nowTime = System.currentTimeMillis()
        endTime = Date("$str $end").time

        return nowTime in startTime until (endTime + 1)
    }

    /**
     * 判断当日是否某个区间内
     */
    fun estimateDay(begin: String, end: String): Boolean {

        startTime = Date("$begin 00:00:00".replace("-", "/")).time
        nowTime = System.currentTimeMillis()
        endTime = Date("$end 23:59:59".replace("-", "/")).time

        return nowTime in startTime until (endTime + 1)
    }

    /**
     * 判断当前时间是否大于结束时间
     */
    fun currentDayAfter(end: String): Boolean {

        nowTime = System.currentTimeMillis()
        endTime = Date("$end 23:59:59".replace("-", "/")).time

        return nowTime > endTime
    }

    fun isValidDate(dateString: String): Boolean {
        val format = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
        format.isLenient = false // 设置为严格模式，确保日期有效
        return try {
            val date = format.parse(dateString)
            date != null // 如果能解析出日期，则返回 true
        } catch (e: Exception) {
            false // 解析失败，则返回 false
        }
    }

    fun isValidTime(timeString: String): Boolean {
        val format = SimpleDateFormat("HHmmss", Locale.getDefault())
        format.isLenient = false // 设置为严格模式，确保时间有效
        return try {
            val time = format.parse(timeString)
            time != null // 如果能解析出时间，则返回 true
        } catch (e: Exception) {
            false // 解析失败，则返回 false
        }
    }

    fun numberToTime(number: String): String {
        val hour = "${number[0]}${number[1]}"
        val mins = "${number[2]}${number[3]}"
        val second = "${number[4]}${number[5]}"
        return "$hour:$mins:$second"
    }

    /**
     *
     * @param startTimeA 目标开始时间
     * @param endTimeA 目标结束时间
     * @param startTimeB 对比开始时间
     * @param endTimeB 对比结束时间
     * @return
     */
    fun checkTimeConflict(startTimeA: String, endTimeA: String, startTimeB: String, endTimeB: String): Boolean {
        val startA = startTimeA.replace(":", "").trim().toLong()
        val endA = endTimeA.replace(":", "").trim().toLong()
        val startB = startTimeB.replace(":", "").trim().toLong()
        val endB = endTimeB.replace(":", "").trim().toLong()

        return !(startA > endB || endA < startB)
    }
}